"""
根据输入内容生成 pdf 文件。
需要安装依赖：pip install fpdf
若为中文需要字体文件行书字体 font.ttf
"""

from fpdf import FPDF
from pywebio import start_server
from pywebio.output import put_text
from pywebio.input import textarea, input, actions, input_group, select, NUMBER


def app():
    add_more = True
    pages = []
    while add_more:
        page = textarea(
            label="Please insert the text for your PDF file",
            placeholder="Type anything you like",
            required=True,
        )
        pages.append(page)
        add_more = actions(
            label="Would you like to add another page?",
            buttons=[
                {'label': 'Yes', 'value': True},
                {'label': 'No', 'value': False}
            ]
        )

    save_location = input("What is the name of your PDF file?", required=True)
    FONTS = ['行书', 'Helvetica', 'Calibri', 'Futura', 'Garamond', 'Times New Roman',
             'Arial', 'Cambria', 'Verdana', 'Rockwell', 'Franklin Gothic']
    text_info = input_group(
        label='Text Fonts and Size',
        inputs=[
            select(
                label='Select your font',
                options=FONTS,
                value='行书',
                name='font'
            ),
            input(
                label='Select your text size',
                type=NUMBER,
                value='16',
                name='size'
            ),
        ]
    )
    # create_pdf(pages, font='Arial', size=16, save_location=save_location)
    create_pdf(
        pages,
        font=text_info['font'],
        size=text_info['size'],
        save_location=save_location,
    )
    put_text("Congratulations! A PDF file is generated for you.")


def create_page(pdf, text: str, font: str, size: int):
    pdf.add_page()
    pdf.add_font('行书', '', 'font.ttf', True)
    pdf.set_font(font, '', size)

    lines = text.split('\n')
    for i, sent in enumerate(lines):
        pdf.cell(40, 10, sent, 0, i + 1)


def create_pdf(pages: list, font: str, size: int, save_location: str = "output.pdf"):
    pdf = FPDF()
    for page in pages:
        create_page(pdf, page, font, size)

    pdf.output(save_location, 'F')


if __name__ == '__main__':
    # 进入脚本所在目录，用于测试
    import os
    from pathlib import Path
    os.chdir(Path(__file__).cwd())

    # 启动 PyWebIO 服务
    start_server(app, port=36535, debug=True)
